import React, {PureComponent} from "react";
import {actionCreators} from "../main/store";
import {connect} from "react-redux";

class LogComponent extends PureComponent {

    constructor(props) {
        super(props);
        this.isComponentWillUnMount = false;
        this.state = {
            logList: [],
            height: (window.document.body.scrollHeight - 64 - 75) + 'px'
        }
    }

    componentDidMount() {
        this.props.connectionRunLogWS((info) => {
            const {logList} = this.state;
            let logListTmp = logList;
            // 每500条清空一次
            if (logListTmp.length > 500) {
                logListTmp = [];
            }
            logListTmp.push(info);
            if (!this.isComponentWillUnMount) {
                this.setState({
                    'logList': logListTmp
                }, () => {
                    this.forceUpdate(() => {
                        this.logContent.scrollTop = this.logContent.scrollHeight;
                    });
                })
            }
        });
    }

    componentWillUnmount() {
        this.isComponentWillUnMount = true;
    }

    render() {
        const {logList} = this.state;
        return (
            <div className={'run-log-content'}
                 style={{width: '100%', height: this.state.height}}
                 ref={(el) => this.logContent = el}>
                {logList.map((item, index, arr) => {
                    return (<p key={index} style={{lineHeight: 2, color: '#fff', fontSize: '16px'}}>{item}</p>);
                })}
            </div>
        );
    }
}

const mapState = (state) => ({});

const mapDispatch = (dispatch) => ({
    connectionRunLogWS(func) {
        actionCreators.connectionRunLogWS(dispatch, func)
    },
});

export default connect(mapState, mapDispatch)(LogComponent);
